/*
 * Copyright (C) 2024-2025 Deepin Technology Co., Ltd.
 *
 * Author:     zhangbingyi <zhangbingyi@uniontech.com>
 *
 * Maintainer: zhangbingyi <zhangbingyi@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "securitytoolswidget.h"
#include "compixmap.h"
#include "securitytools/trustedprotection/trustedprotectiondefinition.h"
#include "securitytoolsmodel.h"
#include "systemrebootdialog.h"
#include "widgets/hiconlistview.h"

class QSpacerItem;
class QListView;
//#include <DFontSizeManager>
#include <QListView>
#include <QToolButton>
#include <QStandardItemModel>

#include <QLabel>
//#include <QScroller>
#include <QScrollBar>
#include <QScrollArea>
#include <QLayoutItem>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDBusConnection>
#include <QSizePolicy>
#include <QMargins>
#include <QDebug>
#include <QListWidget>

SecurityToolsWidget::SecurityToolsWidget(SecurityToolsModel *model, QWidget *parent)
    : QWidget(parent)
    , m_model(model)
    , m_scrollAreaWidgetContents(nullptr)
    , m_systemRebootDialog(nullptr)
{
    this->setAccessibleName("rightWidget_securityToolsWidget");

    // 初始化UI
    initUI();
}

SecurityToolsWidget::~SecurityToolsWidget()
{
}

// 初始化界面
void SecurityToolsWidget::initUI()
{
    // 字体
    QFont ft;
    ft.setBold(true);

    // 弹簧
    QSpacerItem *horizontalSpacer1 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem *horizontalSpacer2 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem *horizontalSpacer3 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem *horizontalSpacer4 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

    // 主布局
    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setContentsMargins(2, 2, 2, 2);

    // 添加滑块
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setFrameShape(QFrame::Shape::NoFrame);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);

    // 添加滑块区域
    m_scrollAreaWidgetContents = new QFrame(scrollArea);
    m_scrollAreaWidgetContents->setAccessibleName("securityToolsWidget_scrollArea");
    m_scrollAreaWidgetContents->setFrameShape(QFrame::NoFrame);

//    // 触屏移动
//    QScroller::grabGesture(scrollArea->viewport(), QScroller::LeftMouseButtonGesture);
//    QScroller *scroller = QScroller::scroller(scrollArea);
//    QScrollerProperties sp;
//    sp.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);
//    scroller->setScrollerProperties(sp);

    // 滑块区域布局
    QVBoxLayout *scrollAreaLayout = new QVBoxLayout(m_scrollAreaWidgetContents);
    scrollAreaLayout->setContentsMargins(50, 27, 50, 27);
    scrollAreaLayout->setSpacing(20);

    // 系统工具标题
    QLabel *systemToolTitle = new QLabel(m_scrollAreaWidgetContents);
    systemToolTitle->setAccessibleName("scrollArea_titleLabel");
    systemToolTitle->setText(tr("System Tools"));
    systemToolTitle->setFont(ft);
//    DFontSizeManager::instance()->bind(systemToolTitle, DFontSizeManager::T5);
    scrollAreaLayout->addWidget(systemToolTitle, 0, Qt::AlignLeft);

    // 系统工具第一行布局
    QHBoxLayout *systemToolLayout_one = new QHBoxLayout();
    systemToolLayout_one->setContentsMargins(0, 0, 0, 0);
    systemToolLayout_one->setSpacing(60);

    QWidget* w;
    // 系统工具 - 登录安全
//    w = getToolWidget("loginSafety", tr("Login Safety"), tr("Manage security levels of system login password"), \
//                      ":/icons/deepin/builtin/icons/def_login_safety_96px.svg", SecurityClickType::LoginSafety);
//    systemToolLayout_one->addWidget(w, 0, Qt::AlignLeft);

    // 系统工具 - 自启动应用
    w = getToolWidget("startupPrograms", tr("Startup Programs"), tr("Manage auto startup programs"), \
                      ":/icons/deepin/builtin/dark/icons/def_startup_programs_96px.svg", SecurityClickType::StartupItem);
    systemToolLayout_one->addWidget(w, 0, Qt::AlignLeft);

    // 系统工具第二行布局
    QHBoxLayout *systemToolLayout_two = new QHBoxLayout();
    systemToolLayout_two->setContentsMargins(0, 0, 0, 0);
    systemToolLayout_two->setSpacing(60);

    // 服务器屏蔽 系统安全等级和可信保护功能
//    if (DSysInfo::UosType::UosServer != SystemType) {
        // 系统工具 - 可信保护
        // 依照要求，在功能不全（dbus服务不存在，或者内核不支持该功能时）场景下
        // 隐藏该入口
        int imaStatus = m_model->getIMAStatus();
        bool exeFilesStatus = m_model->getExeFilesStatus();
        if (exeFilesStatus) {
            // 优先进行执行保护显示判断
            QWidget *wgt = getToolWidget("exeFilesPro", tr("Execution Prevention"), tr("Protect the integrity of core components"),\
                                         ":/icons/deepin/builtin/icons/def_file_trust_protection_96px.svg", SecurityClickType::ExeFilesProtection);
            // 判断加入到系统工具第几行
            systemToolLayout_one->addWidget(wgt, 0, Qt::AlignLeft);
        } else if (imaStatus == IMAStatusDisabled || imaStatus == IMAStatusEnabled) {
            QWidget *wgt = getToolWidget("trustedPro", tr("Trusted Protection"), tr("Protect the integrity of core components"), \
                                         ":/icons/deepin/builtin/icons/def_file_trust_protection_96px.svg", SecurityClickType::FileTrustProtection);
            // 判断加入到系统工具第几行
            systemToolLayout_one->addWidget(wgt, 0, Qt::AlignLeft);
        }

        if (m_model->isShowSystemLevelUi()) {
            // 系统工具 - 系统安全等级
            w = getToolWidget("securityLevel", tr("Security Level"), tr("Set up security levels of your system"), \
                              ":/icons/deepin/builtin/icons/def_system_safe_level_96px.svg", SecurityClickType::SystemSafeLevel);
            systemToolLayout_two->addWidget(w, 0, Qt::AlignLeft);
        }
//    }

    // 将系统工具横向布局加入到滑块布局
    systemToolLayout_one->addItem(horizontalSpacer1);
    scrollAreaLayout->addLayout(systemToolLayout_one);

    // 将系统工具横向布局加入到滑块布局
    systemToolLayout_two->addItem(horizontalSpacer2);
    scrollAreaLayout->addLayout(systemToolLayout_two);

    // 添加分割线
    QFrame *line = new QFrame(m_scrollAreaWidgetContents);
    line->setFixedWidth(630);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    scrollAreaLayout->addWidget(line, 0, Qt::AlignHCenter);

    // 分割线下面再加间隔 - 10
    scrollAreaLayout->addSpacing(10);

    // 网络工具标题
    QLabel *netToolTitle = new QLabel(m_scrollAreaWidgetContents);
    netToolTitle->setText(tr("Network Tools"));
    netToolTitle->setFont(ft);
//    DFontSizeManager::instance()->bind(netToolTitle, DFontSizeManager::T5);
    scrollAreaLayout->addWidget(netToolTitle, 0, Qt::AlignLeft);

    // 网络工具布局
    QHBoxLayout *netToolLayout = new QHBoxLayout();
    netToolLayout->setContentsMargins(0, 0, 0, 0);
    netToolLayout->setSpacing(60);

    if (m_model->isResourceManagerValid()) {
        // 系统工具 - 联网管控
        w = getToolWidget("internetControl", tr("Internet Control"), tr("Allow or disallow the Internet access of applications"), \
                          ":/icons/deepin/builtin/light/icons/def_internet_control_96px.svg", SecurityClickType::NetControlItem);
        netToolLayout->addWidget(w, 0, Qt::AlignLeft);
    }

    // 系统工具 - 流量详情
    w = getToolWidget("dataUsage", tr("Data Usage"), tr("View usage details of applications"), \
                      ":/icons/deepin/builtin/dark/icons/def_data_usage_96px.svg", SecurityClickType::DataUsageItem);
    netToolLayout->addWidget(w, 0, Qt::AlignLeft);

    // 将网络工具工具横向布局加入到滑块布局
    netToolLayout->addItem(horizontalSpacer3);
    scrollAreaLayout->addLayout(netToolLayout);

    // 添加分割线
    QFrame *netToolDeviceSecLine = new QFrame(m_scrollAreaWidgetContents);
    netToolDeviceSecLine->setFixedWidth(630);
    netToolDeviceSecLine->setFrameShape(QFrame::HLine);
    netToolDeviceSecLine->setFrameShadow(QFrame::Sunken);
    scrollAreaLayout->addWidget(netToolDeviceSecLine, 0, Qt::AlignHCenter);

    // 分割线下面再加间隔 10
    scrollAreaLayout->addSpacing(10);

    // 设备安全标题
    QLabel *deviceSecTitle = new QLabel(m_scrollAreaWidgetContents);
    deviceSecTitle->setText(tr("Device Security"));
    deviceSecTitle->setFont(ft);
//    DFontSizeManager::instance()->bind(deviceSecTitle, DFontSizeManager::T5);
    scrollAreaLayout->addWidget(deviceSecTitle, 0, Qt::AlignLeft);

    // 设备安全布局
    QHBoxLayout *deviceSecLayout = new QHBoxLayout();
    deviceSecLayout->setContentsMargins(0, 0, 0, 0);
    deviceSecLayout->setSpacing(60);

    // 设备安全 - USB管控
    w = getToolWidget("usbConnect", tr("USB Connection"), tr("Control the connection of USB storage devices"), \
                      ":/icons/deepin/builtin/icons/def_usb_connection_96px.svg", SecurityClickType::UsbControl);
    deviceSecLayout->addWidget(w, 0, Qt::AlignLeft);

    if (m_model->isShowPeripheralManage()) {
        if (m_model->isAllowPeripheralsManage()) {
            // 设备安全 - 外设管控
            w = getToolWidget("peripheralsManagement", tr("Peripherals Management"), tr("Control the connection of all USB devices"), \
                              ":/icons/deepin/builtin/icons/def_peripherals_management_96px.svg", SecurityClickType::PeripheralsManagement);
            deviceSecLayout->addWidget(w, 0, Qt::AlignLeft);
        }
    }
    // 将设备安全横向布局加入到滑块布局
    deviceSecLayout->addItem(horizontalSpacer4);
    scrollAreaLayout->addLayout(deviceSecLayout);

    // 将滑块添加到主布局
    scrollArea->setWidget(m_scrollAreaWidgetContents);
    verticalLayout->addWidget(scrollArea);
}

QWidget *SecurityToolsWidget::getToolWidget(const QString &sAccessName, const QString &sTitle, const QString &sTip, const QString &sIcon, int nType)
{
    HIconListView* view = new HIconListView(m_scrollAreaWidgetContents);
    view->setMinimumSize(QSize(170, 170));
    view->setFrameShape(QFrame::NoFrame);
    HIconListViewItem _item;
    _item.setText(sTitle);
    _item.setIcon(QIcon(sIcon));
    view->setItems(QList<HIconListViewItem>()<<_item);
    view->setProperty("type", nType);
    connect(view, SIGNAL(itemClicked(int)), this, SLOT(doSecurityItemClicked(int)));
    return view;
    QWidget *widget = new QWidget(m_scrollAreaWidgetContents);
    widget->setAccessibleName("scrollArea_" + sAccessName + "_areaWidget");
    widget->setFixedSize(170, 170);
    QHBoxLayout *widgetLayout = new QHBoxLayout(widget);
    widgetLayout->setContentsMargins(0, 0, 0, 0);
    widgetLayout->setSpacing(0);

    // 添加DListView
    QListWidget *securityView = new QListWidget(widget);
    widget->setAccessibleName("areaWidget_" + sAccessName + "_listView");
    securityView->setProperty("type", nType);
//    securityView->setContentsMargins(0, 0, 0, 0);
    securityView->setMinimumSize(QSize(170, 170));
//    QStandardItemModel *buttonModel = new QStandardItemModel(securityView);
//    securityView->setModel(buttonModel);

    // 形状
    securityView->setFrameShape(QFrame::Shape::NoFrame);
    // 不能编辑触发
    securityView->setEditTriggers(QListView::NoEditTriggers);
    securityView->setResizeMode(QListView::Adjust);
    securityView->setViewMode(QListView::IconMode);
    securityView->setFlow(QListView::LeftToRight);
//    securityView->viewport()->layout()->setMargin(0);
//    securityView->setItemSpacing(0);
//    securityView->setItemMargins(QMargins(0, 0, 0, 18));
//    securityView->setItemRadius(18);

    // 不可以拖拽
    securityView->setDragEnabled(false);
    securityView->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    // 显示图表大小
    securityView->setIconSize(QSize(96, 96));
    securityView->setSpacing(0);
    securityView->setContentsMargins(0, 0, 0, 0);
    // 每个对象大小
//    securityView->setItemSize(QSize(170, 170));

    // 设置其他属性
    securityView->clearSelection();
    securityView->clearFocus();
    securityView->clearMask();
    securityView->setSelectionMode(QAbstractItemView::NoSelection);
    securityView->setTextElideMode(Qt::ElideRight);
    //securityView->setBackgroundType(DStyledItemDelegate::BackgroundType(DStyledItemDelegate::RoundedBackground));

    // 退出模态页面(子页面)后，清除选中效果
    connect(securityView, SIGNAL(clicked(const QModelIndex &)), securityView, SLOT(clearFous(const QModelIndex &)));

//    QStandardItem *item = new QStandardItem;
//    item->setText(sTitle);
//    item->setToolTip(sTip);
//    item->setIcon(QIcon(sIcon));
//    item->setSizeHint(QSize(60, 80));
//    buttonModel->appendRow(item);

    QListWidgetItem *item = new QListWidgetItem;
    item->setText(sTitle);
    item->setToolTip(sTip);
    item->setIcon(QIcon(sIcon));
    item->setSizeHint(QSize(60, 80));
    securityView->addItem(item);

    widgetLayout->addWidget(securityView, 0, Qt::AlignLeft);
    connect(securityView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(doSecurityItemClicked(const QModelIndex &)));

    return widget;
}

// 流量/自启动/联网应用点击槽
void SecurityToolsWidget::doSecurityItemClicked(int nIndex)
{
    Q_UNUSED(nIndex);
    HIconListView *listView = qobject_cast<HIconListView *>(sender());
    int nType = listView->property("type").toInt();

    switch (static_cast<SecurityClickType>(nType)) {
    case StartupItem:
        Q_EMIT notifyShowStartupWidget();
        break;
    case NetControlItem:
        Q_EMIT notifyShowNetControlWidget();
        break;
    case DataUsageItem:
        Q_EMIT notifyShowDataUsageWidget();
        break;
    case UsbControl:
        Q_EMIT notifyShowUsbControlWidget();
        break;
    case LoginSafety:
        Q_EMIT notifyShowLoginSafetyWidget();
        break;
    case SystemSafeLevel:
        Q_EMIT notifyShowSecurityLevelWidget();
        break;
    case FileTrustProtection:
        Q_EMIT notifyShowTrustedProtectionWidget();
        break;
    case ExeFilesProtection: {
        if (m_model->isAllowExeFilesProtection()) {
            Q_EMIT notifyShowExeFilesProtectionWidget();
        }
        break;
    }
    case PeripheralsManagement:
        if (m_model->isSelinuxOpen()) {
            Q_EMIT notifyShowPeripheralsManagementWidget();
        } else {
            m_rebootFlag = false;
            if (m_systemRebootDialog == nullptr) {
                m_systemRebootDialog = new SystemRebootDialog;
                connect(m_systemRebootDialog, SIGNAL(onDialogClose()), SLOT(onDialogClose()));
                connect(m_systemRebootDialog, SIGNAL(sendRebootSystem()), this, SLOT(enableRebootFlag()));
                m_systemRebootDialog->setAttribute(Qt::WA_DeleteOnClose);
                m_systemRebootDialog->setOnButtonClickedClose(true);
                m_systemRebootDialog->show();
            }
        }
        break;
    }
}

//设置因主题改变图标
void SecurityToolsWidget::changeThemeType(ColorType themeType)
{
    Q_UNUSED(themeType);
}

void SecurityToolsWidget::onDialogClose()
{
    m_systemRebootDialog = nullptr;
    if (m_rebootFlag) {
        m_model->oepnSelinux();
    }
}

void SecurityToolsWidget::enableRebootFlag()
{
    m_rebootFlag = true;
}



